# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::BackgroundMigration::SetCorrectVulnerabilityState do
  let(:namespace) { table(:namespaces).create!(name: 'user', path: 'user') }
  let(:users) { table(:users) }
  let(:user) { create_user! }
  let(:project) do
    table(:projects).create!(
      namespace_id: namespace.id,
      project_namespace_id: namespace.id,
      packages_enabled: false)
  end

  let(:vulnerabilities) { table(:vulnerabilities) }

  let!(:vulnerability_with_dismissed_at) do
    create_vulnerability!(
      project_id: project.id,
      author_id: user.id,
      dismissed_at: Time.current
    )
  end

  let!(:vulnerability_without_dismissed_at) do
    create_vulnerability!(
      project_id: project.id,
      author_id: user.id,
      dismissed_at: nil
    )
  end

  let(:detected_state) { 1 }
  let(:dismissed_state) { 2 }

  let(:migration_job) do
    described_class.new(
      start_id: vulnerability_with_dismissed_at.id,
      end_id: vulnerability_without_dismissed_at.id,
      batch_table: :vulnerabilities,
      batch_column: :id,
      sub_batch_size: 1,
      pause_ms: 0,
      connection: ActiveRecord::Base.connection
    )
  end

  describe '#filter_batch' do
    it 'filters out vulnerabilities where dismissed_at is null' do
      expect(migration_job.filter_batch(vulnerabilities)).to contain_exactly(vulnerability_with_dismissed_at)
    end
  end

  describe '#perform' do
    subject(:perform_migration) { migration_job.perform }

    it 'changes vulnerability state to `dismissed` when dismissed_at is not nil' do
      expect { perform_migration }.to change { vulnerability_with_dismissed_at.reload.state }.to(dismissed_state)
    end

    it 'does not change the state when dismissed_at is nil' do
      expect { perform_migration }.not_to change { vulnerability_without_dismissed_at.reload.state }
    end
  end

  private

  def create_vulnerability!(
    project_id:, author_id:, title: 'test', severity: 7, confidence: 7, report_type: 0, state: 1, dismissed_at: nil
  )
    vulnerabilities.create!(
      project_id: project_id,
      author_id: author_id,
      title: title,
      severity: severity,
      confidence: confidence,
      report_type: report_type,
      state: state,
      dismissed_at: dismissed_at
    )
  end

  def create_user!(name: "Example User", email: "user@example.com", user_type: nil)
    users.create!(
      name: name,
      email: email,
      username: name,
      projects_limit: 10
    )
  end
end
